/*
    Project: OCMF (Operant Chamber Management Framework)
    Version: 1.0
    Author: Copyright (C) 2010, Samuel Delaney & Andrew Harvey
    Licence:
        This file is part of OCMF.

            OCMF is free software: you can redistribute it and/or modify
            it under the terms of the GNU General Public License as published by
            the Free Software Foundation, either version 3 of the License, or
            (at your option) any later version.

            OCMF is distributed in the hope that it will be useful,
            but WITHOUT ANY WARRANTY; without even the implied warranty of
            MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
            GNU General Public License for more details.

            You should have received a copy of the GNU General Public License
            along with OCMF.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "Trial.h"
#include "mainwindow.h"

Trial::Trial(QDomElement trialElement, Experiment * experiment)
{
    qDebug("Hello");
    //retrieve all action elements at current level
    QDomNodeList actionNodeList = trialElement.childNodes();

    //check that there are three collections of action (pretrial,cards,posttrial)
    if(actionNodeList.count() != 3)
    {
        qDebug("Trial XML Incorrect!");
        return;
    }

    //parse pre-trial actions
    qDebug("Parsing Pre Action Trials");
    PreTrialActions = new ActionCollection(actionNodeList.at(0),this);

    //parse images
    QDomNodeList imagesNodeList = actionNodeList.at(1).childNodes();

    //iterate over all images and add to vector
    qDebug("Parsing Trial Images...");
    for(int i = 0; i < imagesNodeList.count(); i++)
    {
        Images.push_back(new Image(imagesNodeList.at(i).toElement(), this));
    }

    //parse post-trial actions
    qDebug("Parsing Post Trial Actions");
    PostTrialActions = new ActionCollection(actionNodeList.at(2),this);
}

void Trial::Do()
{
    //log result
    Action::WriteResult(ToResultXml());

    //do pretrial actions
    PreTrialActions->Do();

    //display images on gui
    //Experiment->Server->MainWindow
    //((MainWindow *)Owner()->Owner()->Owner())->DisplayImages(&Images);

    //do posttrial actions
    PostTrialActions->Do();


    //((MainWindow *)Owner()->Owner()->Owner())->RemoveImages(&Images);
}

QDomElement Trial::ToResultXml()
{
    QDomElement trialElement;

    //set the tag value
    trialElement.setTagName("Trial");

    //set the timestamp attribute
    trialElement.setAttribute("TimeStamp", TimeStamp.toString(Qt::ISODate));

    //set the experimentid attribute
    trialElement.setAttribute("Index", OwnerExperiment()->currentActionIndex);

    //return the xml node
    return trialElement;
}

Experiment * Trial::OwnerExperiment()
{
    return ownerExperiment;
}
